package cn.tuling.standard;

import java.util.ArrayList;
import java.util.List;

/**
 * 常规实现
 */
public class IteratorTest {
    public static void main(String[] args) {
        Aggregate<String> aggregate = new ConcreteAggregate<>();
        aggregate.add("a");
        aggregate.add("b");
        aggregate.add("c");
        aggregate.add("d");

        Iterator<String> iterator = aggregate.iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            System.out.println(next);
        }
    }
}

interface Iterator<E> {
    public E next();

    public boolean hasNext();

    public boolean remove();
}

class ConcreteIterator<E> implements Iterator {
    private List<E> list = new ArrayList<>();
    private int cursor = 0;

    public ConcreteIterator(List<E> list) {
        this.list = list;
    }

    @Override
    public E next() {
        E object = null;
        if (hasNext()) {
            object = this.list.get(cursor++);
        }
        return object;
    }

    @Override
    public boolean hasNext() {
        if (cursor >= list.size()) {
            return false;
        }

        return true;
    }

    @Override
    public boolean remove() {
        list.remove(cursor);
        return true;
    }
}

interface Aggregate<E> {
    void add(E object);

    void remove(E object);

    Iterator<E> iterator();
}

class ConcreteAggregate<E> implements Aggregate<E> {
    List<E> list = new ArrayList<>();

    @Override
    public void add(E object) {
        this.list.add(object);
    }

    @Override
    public void remove(E object) {
        this.list.remove(object);
    }

    @Override
    public Iterator<E> iterator() {
        return new ConcreteIterator<E>(list);
    }
}